/**
 * 
 */
package gui;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.*;
import java.util.ArrayList;

import elements.HostNode;
import elements.Link;
import elements.Node;
import widgets.LinkWidget;
import widgets.NodeWidget;

/**
 * @author danielsmw
 *
 */
public class AppletDriver extends Applet implements Runnable, MouseListener {

	Image offscreen;
	Thread animation;
	NodeWidget a, b;
	LinkWidget link;
	ArrayList<NodeWidget> nodes = new ArrayList<NodeWidget>();
	
	// These are the last clicked positions of the cursor.
	int clickX, clickY;
	
	public void start() {
		animation = new Thread(this);
		animation.start();
		addMouseListener(this);
	}
	
	public void init() {
		a = new NodeWidget(20, 100, new Node("a", 100, 200.5));
		b = new NodeWidget(60, 170, new Node("b", 150, 232.3));
		nodes.add(a); nodes.add(b);
		link = new LinkWidget(new Link(a.getNode(), b.getNode()));
	}
	
	public void run () {
		Thread t = Thread.currentThread();
		while (t == animation) {
			try {
				Thread.sleep(100);
			} 
			catch (Exception e) {
				System.out.println("AppletDriver: "+e);
				break;
			}
			repaint();
		}
	}
	
	public void update (Graphics g) {
		paint(g);
	}
	
	public void paint (Graphics g) {
		offscreen = createImage(getSize().width, getSize().height);
		Graphics2D g2d = (Graphics2D)offscreen.getGraphics();
		g2d.setColor(Color.WHITE);
		g2d.fillRect(0, 0, getSize().width, getSize().height);
		
		g2d.setColor(Color.BLACK);
		
		a.drawMe(g2d);
		b.drawMe(g2d);
		link.drawMe(g2d);
		
		g2d.dispose();
		g.drawImage(offscreen, 0, 0, this);
		
	}

	public void mouseClicked(MouseEvent e) {
		long starttime = System.currentTimeMillis();
		System.out.println("Clicked: "+e.getX()+","+e.getY());
		clickX = e.getX();
		clickY = e.getY();
		
		Point p = new Point(clickX, clickY);
		NodeWidget selectedNode = null;
		long starttime1 = System.currentTimeMillis();
		for(NodeWidget n: nodes) {
			if (n.encompasses(p)) {
				selectedNode = n;
			}
		}
		long endtime1 = System.currentTimeMillis();
		
		if (selectedNode != null) {
			if (selectedNode.getFocus() != 2) {
				selectedNode.setSelected();
			}
			else {
				selectedNode.setUnfocused();
			}
		}
		long endtime = System.currentTimeMillis();
	}

	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}
}
